//
//  UpdateBankViewController.swift
//  d11
//
//  Created by rhonin on 2018/11/2.
//  Copyright © 2018年 Tech_001. All rights reserved.
//

import UIKit
import SwiftyJSON

class UpdateBankViewController: UpdateRootViewController {
    // 距离父视图顶部间距
    @IBOutlet weak var bottomViewTopConstraint: NSLayoutConstraint!
    
    @IBOutlet weak var buttonSure: UIButton!
    var indexSelect = 0
    @IBOutlet weak var openbankName: UITextField!
    
    @IBOutlet weak var telephone: UILabel!
    @IBOutlet weak var countLab: UILabel!
    @IBOutlet weak var bankName: UITextField!
    @IBOutlet weak var butGetCode: UIButton!
    @IBOutlet weak var viewFive: UIView!
    @IBOutlet weak var viewFour: UIView!
    @IBOutlet weak var viewThird: UIView!
    @IBOutlet weak var viewSec: UIView!
    @IBOutlet weak var viewCome: UIView!
    @IBOutlet weak var note: UITextField!
    @IBOutlet weak var code: UITextField!
    @IBOutlet weak var userAccount: UITextField!
    @IBOutlet weak var userName: UITextField!
    var array = [JSON]()
    var timerN : Timer?
    var isWithdraw : Bool = false
    //获取验证码的手机号：
    override func viewDidLoad() {
        super.viewDidLoad()
        // 设置导航栏默认返回按钮
        self.leftButtonActionWithImg("icon_default_back")
        self.bottomViewTopConstraint.constant = kNavigationBarHeight
        
        for viewin in self.view.subviews {
            if viewin.isKind(of: UIView.self){
                viewin.layer.borderColor = RGBAlpa(219,219,219,1).cgColor
            }
        }
        self.telephone.text = "获取验证码的手机号码：" + (GlobalInfo.baseInfoData != nil ? GlobalInfo.baseInfoData!.mobile : "")
        self.title = "绑定银行卡"
        // Do any additional setup after loading the view.
        weak var this = self
        
        let layerGradientCode = CAGradientLayer()
        layerGradientCode.colors = [
            UIColor.init(red: 1, green: 0.78, blue: 0.45, alpha: 1).cgColor,
            UIColor.init(red: 0.99, green: 0.57, blue: 0.33, alpha: 1).cgColor
        ]
        layerGradientCode.frame = CGRect(x: 0, y: 0, width: buttonSure.frame.width, height: buttonSure.frame.height+50)
        buttonSure.layer.addSublayer(layerGradientCode)
        buttonSure.layer.cornerRadius = 5
        
        butGetCode.clipsToBounds = true
        butGetCode.layer.cornerRadius = 6
        butGetCode.layer.borderColor = RGBAlpa(255,198,116,1).cgColor
        butGetCode.layer.borderWidth = 0.5
        RequestHelper.post(atPath: "/clientsAPIs/getbank", withData: Dictionary(), withCompletion: { data in
            let json = JSON(data)
            if json.arrayValue.count > 0{
               this?.array = json.arrayValue
            }
            
        },withError: {_ in
             UIHelper.alertSimpleMessage(about: "服务器异常，\(getErrorString())", withDescription: "", in: self)
        })
        let item = UIBarButtonItem(title: "", style: .plain, target: self, action: nil)
        self.navigationItem.backBarButtonItem = item;
        self.userInfoDetail()
    }
    
    //个人详情数据
    func userInfoDetail() -> Void {
        RequestHelper.post(atPath: "/clientsAPIs/GetProfileInfo",  withData:Dictionary(), withCompletion: { data in
            //  let snsns = try JSONSerialization.jsonObject(with: data, options: [])
            let json = JSON(data)
            GlobalInfo.baseInfoData = UserInfoModel.changeJsonTomModel(json: json[0])
            DispatchQueue.main.async {
               self.telephone.text = "获取验证码的手机号码：" + (GlobalInfo.baseInfoData != nil ? GlobalInfo.baseInfoData!.mobile : "")
            }
        }, withError: { error in
             UIHelper.alertSimpleMessage(about: "服务器异常，\(getErrorString())", withDescription: "", in: self)
        })
    }
    @IBAction func buttonCount(_ sender: Any) {
    
        self.startTimer()
        RequestHelper.post(atPath: "/clientsAPIs/getmobileauthorisationcode", withData: Dictionary(), withCompletion: { data in
            let json = JSON(data)
            let code = json["success"].boolValue
            if code  {
                DispatchQueue.main.async {
                    UIHelper.alertSimpleMessage(about: "获取短信验证码成功", withDescription: "请查看您的短信", in: self)

                }
            }else{
                DispatchQueue.main.async {

                    UIHelper.alertSimpleMessage(about: "获取短信验证码失败", withDescription: json["msg"].stringValue, in: self)

                }
            }
        },withError: {_ in
             UIHelper.alertSimpleMessage(about: "服务器异常，\(getErrorString())", withDescription: "", in: self)
        })
    }
    func startTimer() {
        // 定义需要计时的时间
        self.seconds = GlobalInfo.codeTimeInterval
       weak var this = self
        // 在global线程里创建一个时间源
        let timer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
        // 设定这个时间源是每秒循环一次，立即开始
        timer.scheduleRepeating(deadline:  .now(), interval: .seconds(1))
        // 设定时间源的触发事件
        timer.setEventHandler(handler: {
            // 每秒计时一次
           
            // 返回主线程处理一些事件，更新UI等等
            
            DispatchQueue.main.async {
                if let strong = this{
                    strong.seconds -=  1
                    if  strong.seconds <= 0 {
                        timer.cancel()
                    }
                }
                
            }
        })
        // 启动时间源
        timer.resume()
    }
    
    var seconds : NSInteger = 60{
        willSet{
            if newValue == 0 {
                 butGetCode.isUserInteractionEnabled = true
                countLab.text = "重新获取"
              //  butGetCode.setTitle("获取验证码", for: UIControlState.normal)
            }else{
                butGetCode.isUserInteractionEnabled = false
                 countLab.text = "\(newValue)s"
            //    butGetCode.setTitle("\(newValue)s", for: UIControlState.normal)
            }
        }
    }
    
   @objc func countSecond()  {
        if seconds>1 {
            //.........
            seconds -= 1
        }else {
            stopTimer()
        }
    }
    
    // 4.停止计时
    func stopTimer() {
        if timerN != nil {
            timerN!.invalidate() //销毁timer
            timerN = nil
        }
    }
    var loadViews:MBProgressHUD?
    
    @IBAction func submit(_ sender: Any) {
        if self.bankName.text!.count == 0 {
            UIHelper.alertSimpleMessage(about: "请输入银行卡", withDescription: "", in: self)
            return
        }else if self.userName.text!.count == 0{
            UIHelper.alertSimpleMessage(about: "请输入开户名", withDescription: "", in: self)
            return
        }else if self.userAccount.text!.count == 0{
            UIHelper.alertSimpleMessage(about: "请输入开户账号", withDescription: "", in: self)
            return
        }else if self.openbankName.text!.count == 0{
            UIHelper.alertSimpleMessage(about: "请输入开户行", withDescription: "", in: self)
            return
        }else if self.code.text!.count == 0{
            UIHelper.alertSimpleMessage(about: "请输入验证码", withDescription: "", in: self)
            return
        }
//        else if self.note.text!.count == 0{
//            UIHelper.alertSimpleMessage(about: "请输入备注", withDescription: "", in: self)
//            return
//        }
        loadViews = MBProgressHUD.showMessageNoHiden("正在提交..", to: self.view)
        weak var this = self
        let jsonSelect = array[indexSelect]
        let dic = ["bankcode":jsonSelect["bankcode"].stringValue,"card":self.userAccount.text ?? "","account":self.userName.text ?? "","note":self.note.text ?? "","mobile_code":self.code.text ?? "","banknode":self.openbankName.text!]
        RequestHelper.post(atPath: "/clientsAPIs/savebankcard", withData: dic, withCompletion: { data in
            let json = JSON(data)
            if json["success"].boolValue{
                 DispatchQueue.main.async {
                    UIHelper.alertSimpleMessage(about: "绑定成功", withDescription: "", in: self)
                    this?.perform(#selector(this?.popcont), with: nil, afterDelay: 0.5)
                    this?.loadViews?.removeFromSuperview()
                }
            }else{
                 DispatchQueue.main.async {
                    this?.loadViews?.removeFromSuperview()
                    UIHelper.alertSimpleMessage(about: "绑定失败", withDescription: json["msg"].stringValue, in: self)
                    
                }
            }
        },withError: {_ in
             UIHelper.alertSimpleMessage(about: "服务器异常，\(getErrorString())", withDescription: "", in: self)
        })
    }

    @objc func popcont()  {
        if self.isWithdraw == true{ //取款跳转过来的
            let vc = WithdrawVC()
            vc.type = 3
            self.navigationController?.pushViewController(vc, animated: true)
        }else{
            self.navigationController?.popViewController(animated: true)
        }
       
    }
    
    @IBAction func selectBank(_ sender: Any) {
        self.view.endEditing(true)
        var arrayString = [String]()
        for json in array {
           let string =  json["bankname"].stringValue
            arrayString.append(string)
        }
        weak var this  = self
        UsefulPickerView.showSingleColPicker("", data: arrayString, defaultSelectedIndex: 0) { (selecedIndex, title) in
            this?.indexSelect = selecedIndex
            this?.bankName.text = title
        }
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
